package com.lw.leetcode.back.b;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 40. 组合总和 II
 * 剑指 Offer II 082. 含有重复元素集合的组合
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/18 12:11
 */
public class CombinationSum2 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> all = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return all;
        }
        Arrays.sort(candidates);
        List<Integer> list = new ArrayList<>();
        find(candidates, target, all, list, 0);
        return all;
    }


    private static boolean find(int[] candidates, int target, List<List<Integer>> all, List<Integer> list, int indx) {
        if (target == 0) {
            all.add(new ArrayList<>(list));
            return true;
        }
        if (target < 0) {
            return false;
        }
        int length = candidates.length;
        int size = list.size();
        for (int i = indx; i < length; i++) {
            int candidate = candidates[i];
            list.add(candidate);
            boolean b = find(candidates, target - candidate, all, list, i + 1);
            list.remove(size);
            if (!b) {
                break;
            }
            while (++i < length) {
                if (candidates[i] != candidate) {
                    break;
                }
            }
            --i;
        }
        return true;
    }
}
